﻿using System;
using System.Collections;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke.Common.Lists;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Profile;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security;
using DotNetNuke.Security.Profile;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.UI.WebControls;

using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using DotNetNuke.Framework;
using DotNetNuke.UI.WebControls;
using DotNetNuke.Services.Exceptions;

using BuSm = VLUNewsBusiness.VLUSitemap;
using System.Collections.Generic;

namespace VLUNewsUI.VLUSitemap
{
    public partial class Sitemaps : PortalModuleBase, IActionable
    {
        #region Private Members
        private int _ParentID = -1;
        private string _CommandName = string.Empty;
        #endregion

        #region Private Methods
        void BindingDataGrid(int pParentID = -1)
        {
            dgdSitemap.DataSource = BuSm.Sitemap.Instance().GetsChildren(pParentID);
            Localization.LocalizeDataGrid(ref dgdSitemap, LocalResourceFile);
            dgdSitemap.DataBind();
        }
        void BindingDataList(IList pParents)
        {
            dtlParent.DataSource = pParents;
            dtlParent.DataBind();
        }
        #endregion

        #region Event Handlers
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Init runs when the control is initialised
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //this.AddActionHandler(new ActionEventHandler((s , e1) =>
            //    {
            //        int itemp = 1;
            //    }));

            jQuery.RequestDnnPluginsRegistration();

            foreach (DataGridColumn column in dgdSitemap.Columns)
            {
                if (ReferenceEquals(column.GetType(), typeof(ImageCommandColumn)))
                {
                    //Manage Delete Confirm JS
                    var imageColumn = (ImageCommandColumn)column;
                    imageColumn.Visible = IsEditable;
                    if (imageColumn.CommandName == "Delete")
                    {
                        imageColumn.OnClickJS = Localization.GetString("DeleteItem");
                    }

                    //Manage Edit Column NavigateURLFormatString
                    if (imageColumn.CommandName == "Edit")
                    {
                        //so first create the format string with a dummy value and then
                        //replace the dummy value with the FormatString place holder
                        string formatString = EditUrl("SitemapID", "KEYFIELD", "Edit");
                        formatString = formatString.Replace("KEYFIELD", "{0}");
                        imageColumn.NavigateURLFormatString = formatString;
                    }

                    //Localize Image Column Text
                    if (!String.IsNullOrEmpty(imageColumn.CommandName))
                    {
                        imageColumn.Text = Localization.GetString(imageColumn.CommandName, LocalResourceFile);
                    }
                }// if
            }// foreach
        }// Init

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            dgdSitemap.ItemDataBound += OnDataGridSitemap_ItemDataBound;
            dgdSitemap.ItemCommand += OnDataGridSitemap_ItemCommand;
            dgdSitemap.PreRender += OnSitemap_PreRender;
            dtlParent.ItemCommand += OnParent_ItemCommand;
            if (ViewState["ParentID"] == null)
            {
                if (Request.QueryString["ParentID"] != null)
                    _ParentID = Int32.Parse(Request.QueryString["ParentID"]);
                ViewState["ParentID"] = _ParentID;
            }
            lblParentID.Text = _ParentID.ToString();
            if (!IsPostBack)
            {
                IList lstParent = BuSm.Sitemap.Instance().GetsParentByParentID(_ParentID);
                if (lstParent == null)
                    lstParent = new List<KeyValuePair<int, string>>();
                lstParent.Insert(0, new KeyValuePair<int, string>(-1, Localization.GetString("RootParent", LocalResourceFile)));
                BindingDataList(lstParent);
                BindingDataGrid(_ParentID);
            }

            // Release Business Object.
            BuSm.Sitemap.Release();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        protected void OnSitemap_PreRender(object sender, EventArgs e)
        {
            if (!(_CommandName.Equals("Up") || _CommandName.Equals("Down")))
                dgdSitemap.SelectedIndex = -1;
        }

        protected void OnParent_ItemCommand(object source, DataListCommandEventArgs e)
        {
            _CommandName = e.CommandName;
            int iSitemapID = Int32.Parse(e.CommandArgument.ToString());
            _ParentID = iSitemapID;
            ViewState["ParentID"] = _ParentID;
            lblParentID.Text = _ParentID.ToString();
            List<KeyValuePair<int, string>> lst = new List<KeyValuePair<int, string>>();
            foreach (DataListItem item in dtlParent.Items)
            {
                CommandButton cmd = (CommandButton)item.Controls[1];
                lst.Add(new KeyValuePair<int, string>(int.Parse(cmd.CommandArgument), cmd.Text));
                if (item == e.Item)
                {
                    break;
                }
            }

            BindingDataList(lst);

            BindingDataGrid(int.Parse(e.CommandArgument.ToString()));
        }

        protected void OnDataGridSitemap_ItemDataBound(object source, DataGridItemEventArgs e)
        {
            var item = e.Item;
            if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem)
            {
                var imgColumnControl = item.Controls[0].Controls[0];
                if (imgColumnControl is HyperLink)
                {
                    var editLink = (HyperLink)imgColumnControl;
                    editLink.NavigateUrl = EditUrl("SitemapID", ((System.Web.UI.WebControls.TableCell)(item.Controls[2])).Text, "Edit", "ParentID=" + ViewState["ParentID"]);
                }

            }
        }

        protected void OnDataGridSitemap_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            _CommandName = e.CommandName;
            switch (e.CommandName)
            {
                case "Delete":
                    {
                        OnDeleteCommand(source, e);
                        break;
                    }
                case "Edit":
                    {
                        OnEditCommand(source, e);
                        break;
                    }
                case "Up":
                    {
                        OnUpCommand(source, e);
                        break;
                    }
                case "Down":
                    {
                        OnDownCommand(source, e);
                        break;
                    }
                case "Select":
                    {
                        OnSelectCommand(source, e);
                        break;
                    }
            }
        }

        protected void OnDeleteCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                var iSitemapID = Int32.Parse(e.CommandArgument.ToString());
                int result = BuSm.Sitemap.Instance().Delete(iSitemapID);
                switch (result)
                {
                    case -1:
                    case 0:
                    case 2:
                        {
                            DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SitemapDeleteError", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                            break;
                        }
                    case 1:
                        {
                            DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SitemapDeleted", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess);
                            break;
                        }
                }
                BindingDataGrid();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnEditCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                var iSitemapID = Int32.Parse(e.CommandArgument.ToString());
                Response.Redirect(EditUrl("SitemapID", iSitemapID.ToString(), "Edit", "ParentID=" + ViewState["ParentID"]));
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnUpCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                dgdSitemap.SelectedIndex = e.Item.ItemIndex;
                var iSitemapID = Int32.Parse(e.CommandArgument.ToString());
                if (0 == e.Item.ItemIndex)
                    return;
                DataGridItem item = dgdSitemap.Items[0];
                List<TableCellCollection> lst = new List<TableCellCollection>();
                int i;
                for (i = 1; i < dgdSitemap.Items.Count; i++)
                {
                    if (dgdSitemap.Items[i] == e.Item)
                    {
                        lst.Add(dgdSitemap.Items[i].Cells);
                        lst.Add(item.Cells);
                        break;
                    }
                    else
                    {
                        lst.Add(item.Cells);
                        item = dgdSitemap.Items[i];
                    }
                }
                for (int j = i + 1; j < dgdSitemap.Items.Count; j++)
                {
                    lst.Add(dgdSitemap.Items[j].Cells);
                }

                var data = lst.Select(p => new
                {
                    SitemapID = p[4].Text,
                    SitemapName = p[5].Text,
                    IsSecurity = p[6].Text
                });

                dgdSitemap.DataSource = data;
                dgdSitemap.DataBind();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnDownCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                dgdSitemap.SelectedIndex = e.Item.ItemIndex;
                var iSitemapID = Int32.Parse(e.CommandArgument.ToString());
                if (dgdSitemap.Items.Count - 1 == e.Item.ItemIndex)
                    return;
                List<TableCellCollection> lst = new List<TableCellCollection>();
                int i;
                for (i = 0; i < dgdSitemap.Items.Count; i++)
                {
                    if (dgdSitemap.Items[i] == e.Item)
                    {
                        lst.Add(dgdSitemap.Items[i+1].Cells);
                        lst.Add(dgdSitemap.Items[i].Cells);
                        break;
                    }
                    else
                    {
                        lst.Add(dgdSitemap.Items[i].Cells);
                    }
                }
                for (int j = i + 2; j < dgdSitemap.Items.Count; j++)
                {
                    lst.Add(dgdSitemap.Items[j].Cells);
                }

                var data = lst.Select(p => new
                {
                    SitemapID = p[4].Text,
                    SitemapName = p[5].Text,
                    IsSecurity = p[6].Text
                });

                dgdSitemap.DataSource = data;
                dgdSitemap.DataBind();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnSelectCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                int iSitemapID = Int32.Parse(e.CommandArgument.ToString());
                _ParentID = iSitemapID;
                ViewState["ParentID"] = _ParentID;
                lblParentID.Text = _ParentID.ToString();
                string sSitemapName = e.Item.Cells[3].Text;
                List<KeyValuePair<int, string>> lst = new List<KeyValuePair<int, string>>();
                foreach (DataListItem item in dtlParent.Items)
                {
                    CommandButton cmd = (CommandButton)item.Controls[1];
                    lst.Add(new KeyValuePair<int, string>(int.Parse(cmd.CommandArgument), cmd.Text));
                }
                lst.Add(new KeyValuePair<int, string>(iSitemapID, sSitemapName));

                BindingDataList(lst);
                // Binding data grid.
                BindingDataGrid(iSitemapID);
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        #endregion Event Handlers
        
        #region IActionable Members
        //public void RaisePostBackEvent(String eventArgument)
        //{
        //    if (eventArgument.ToUpper() == "ARGUMENT")
        //    {

        //    }
        //}
        //private void SitemapAction_Click(object sender, DotNetNuke.Entities.Modules.Actions.ActionEventArgs e)
        //{
        //    if (ViewState["ParentID"] == null)
        //    {
        //        if (Request.QueryString["ParentID"] != null)
        //            _ParentID = Int32.Parse(Request.QueryString["ParentID"]);
        //        ViewState["ParentID"] = _ParentID;
        //    }
        //    if (e.Action.CommandName == ModuleActionType.AddContent)
        //    {
        //        e.Action.Url = EditUrl("ParentID", ViewState["ParentID"].ToString(), "");
        //    }
        //}
        public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions
        {
            get
            {
                //ModuleActionCollection Actions = new ModuleActionCollection();
                //Actions.Add(ModuleContext.GetNextActionID(),
                //            "Bla",
                //            "",
                //            "",
                //            "",
                //            "javascript:" + Page.ClientScript.GetPostBackEventReference(this, "ARGUMENT"),
                //            Page.ClientScript.GetPostBackEventReference(this, "ARGUMENT"),
                //            false,
                //            DotNetNuke.Security.SecurityAccessLevel.Edit,
                //            true,
                //            false);
                //return Actions;

                ModuleActionCollection actions = new ModuleActionCollection();
                ModuleAction action = new ModuleAction(ModuleContext.GetNextActionID());
                action.Title = Localization.GetString("ActionAdd", LocalResourceFile);
                action.CommandName = "";
                action.CommandArgument = "";
                action.Url = EditUrl("ParentID", _ParentID.ToString());
                action.UseActionEvent = true;
                action.Secure = SecurityAccessLevel.Edit;
                action.Icon = "add.gif";
                actions.Add(action);
                return actions;

                //var actions = new ModuleActionCollection
                //                  {
                //                      {
                //                          GetNextActionID(), Localization.GetString("ActionAdd", LocalResourceFile), ModuleActionType.AddContent, "", "add.gif",
                //                          EditUrl(), false, SecurityAccessLevel.Edit, true, false
                //                      }
                //                  };
                //return actions;
            }
        }

        #endregion
    }
}